package gpstools.calc;

import gpstools.TrainingPoint;

public class PowerCalculator {

    /** time in ms */
    private long time = 0;
    /** time * power sum */
    private double sum = 0;
    /** maximum power */
    private int max = 0;

    /** most recently added point */
    private TrainingPoint last = null;

    public PowerCalculator add(final TrainingPoint point) {
        if (isValid(point)) {
            if (last != null) {
                if (point.getTime() < last.getTime()) {
                    return this;
                }

                final double timeDiff = point.getTime() - last.getTime();
                final int power = point.getPower().intValue();

                this.sum += timeDiff * power;
                this.time += timeDiff;

                if (power > max) {
                    max = power;
                }
            } else {
                /* first point */
                max = point.getPower().intValue();
            }
        }
        last = point;
        return this;
    }

    private boolean isValid(TrainingPoint point) {
        return point.getPower() != null;
    }

    /**
     * returns average power
     * 
     * @return average power or <code>null</code> when no points were added to calculation
     */
    public Integer getAverage() {
        if (time == 0 && last == null) {
            /* no data */
            return null;
        } else if (time == 0) {
            /* only one point */
            return last.getPower();
        } else {
            /* many points */
            return (int) Math.round(sum / time);
        }
    }

    /**
     * returns maximum power
     * 
     * @return maximum power or <code>null</code> when no points were added to calculation
     */
    public Integer getMaximum() {
        if (last == null) {
            /* no data */
            return null;
        } else {
            return max;
        }
    }

}
